package relu.R.birds;
import relu.R.landscape.*;
import jfm.utils.*;

public class BreedingHabitats {
	
	// Requires a normalized probability map
	public static double[] samplePoint(double[][] pmap,double side,double rand){
		double cumP=0;
		int foundi=pmap.length-1;
		int foundj=pmap.length-1;
		findij:
		for(int i=0;i<pmap.length;i++){
			for(int j=0;j<pmap.length;j++){
				cumP+=pmap[i][j];
				if ( cumP >= rand){
					foundi=i;
					foundj=j;
					break findij;
				}				
			}
		}
		double dside=side/pmap.length;
		double[] point=new double[2];
		point[0]=dside*(foundi+rand);
		point[1]=dside*(foundj+rand);
		return point;
	}
	
	public static double[][] getBreedingProbabilityMap(SpatialLandscape ls,int gridSize){
		double[][] probs=new double[gridSize][gridSize];
		double[] gridBins=new double[gridSize+1];
		gridBins[0]=0;
		double binWidth=ls.sideLength/gridSize;
		for(int i=0;i<gridSize;i++){
			gridBins[i+1]=gridBins[i]+binWidth;
		}
		double total=0;
		for(int i=0;i<gridSize;i++){
			for(int j=0;j<gridSize;j++){
				double xmid=gridBins[i]+binWidth/2;
				double ymid=gridBins[j]+binWidth/2;
				LSFarm closest=ls.owningFarm(xmid, ymid);
				probs[i][j]=getHabitatProbability(closest);
	//			System.out.println(xmid+" "+ymid+" "+closest.location.area+" "+closest.location.xPos+" "+closest.location.yPos);
				total+=probs[i][j];
			}
		}
		if ( total==0){throw new Error("Zero probability in habitat map");};
		for(int i=0;i<gridSize;i++){
			for(int j=0;j<gridSize;j++){
				probs[i][j]/=total;
			}
		}
		return probs;
	}
	
	public static double getMaxBreeders(LSFarm farm,BirdSpecies sp){
		double hedgeRequirement=sp.hedgeBreedingRequirement;
		return farm.getHedgeDensity()*farm.area/hedgeRequirement;
	}
	
	public static double getHabitatProbability(LSFarm farm){
		double p=0;
		p+=farm.getHedgeDensity();	
//		System.out.println(p);
		return p;
	}
	
}
